package com.linln.admin.personMch.controller;

import com.california.pay.consts.OrderStatus;
import com.linln.admin.core.constant.AdminConst;
import com.linln.admin.core.enums.ResultEnum;
import com.linln.admin.core.enums.StatusEnum;
import com.linln.admin.core.exception.ResultException;
import com.linln.admin.core.shiro.ShiroUtil;
import com.linln.admin.personMch.consts.SettleStatus;
import com.linln.admin.personMch.domain.MchInfo;
import com.linln.admin.personMch.domain.SettleAccount;
import com.linln.admin.personMch.service.PayOrderService;
import com.linln.admin.personMch.service.SettleAccountService;
import com.linln.admin.personMch.validator.SettleAccountForm;
import com.linln.admin.system.domain.User;
import com.linln.admin.system.service.UserService;
import com.linln.core.utils.FormBeanUtil;
import com.linln.core.utils.ResultVoUtil;
import com.linln.core.vo.ResultVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author 小懒虫
 * @date 2019/01/04
 */
@Controller
@RequestMapping("/settleAccount")
public class SettleAccountController {

    @Autowired
    private SettleAccountService settleAccountService;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private UserService userService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("/settleAccount/index")
    public String index(Model model) {
        if (!ShiroUtil.getSubject().getId().equals(AdminConst.ADMIN_ID)) {
            model.addAttribute("isAdmin", false);
        }else{
            model.addAttribute("isAdmin", true);
        }
        return "/personMch/settleAccount/index";
    }

    @GetMapping("/data")
    @ResponseBody
    public ResultVo data(Model model, SettleAccount settleAccount,
                         @RequestParam(value="page",defaultValue="1") int pageIndex,
                         @RequestParam(value="size",defaultValue="10") int pageSize){
        //非超级管理员
        if (!ShiroUtil.getSubject().getId().equals(AdminConst.ADMIN_ID)) {
            settleAccount.setMchNo(ShiroUtil.getSubject().getMchInfo().getMchNo());
        }
        Page<SettleAccount> list = settleAccountService.getPageList(settleAccount, pageIndex, pageSize);
        return ResultVoUtil.success("加载数据完成！", list);
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("/settleAccount/add")
    public String toAdd(Model model){
        MchInfo curMch = userService.getId(ShiroUtil.getSubject().getId()).getMchInfo();
        Long totalAmount = payOrderService.sumPayAmountByOrderStatus
                (OrderStatus.PAY_SUCC,curMch.getMchNo());
        if(totalAmount == null){
            totalAmount = 0L;
        }
        model.addAttribute("mchNo", curMch.getMchNo());
        model.addAttribute("maxAmount", totalAmount-curMch.getSettleAmount());
        return "/personMch/settleAccount/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit")
    @RequiresPermissions("/settleAccount/edit")
    public String toEdit(@RequestParam("id") String id, Model model){
        SettleAccount settleAccount = settleAccountService.getId(id);
        model.addAttribute("settleAccount",settleAccount);
        return "/personMch/settleAccount/add";
    }

    /**
     * 保存添加/修改的数据
     * @param settleAccountForm 表单验证对象
     */
    @PostMapping({"/add","/edit"})
    @RequiresPermissions({"/settleAccount/add","/settleAccount/edit"})
    @ResponseBody
    public ResultVo save(@Validated SettleAccountForm settleAccountForm){
        // 将验证的数据复制给实体类
        SettleAccount settleAccount = new SettleAccount();
        if(settleAccountForm.getId() != null){
            settleAccount = settleAccountService.getId(settleAccountForm.getId());
        }

        FormBeanUtil.copyProperties(settleAccountForm, settleAccount);

        if(settleAccountForm.getId() == null){
            String randId = DateFormatUtils.format(new Date(),("yyyyMMddHHmmssSSS"))
                    +  RandomUtils.nextInt(1000,9999);
            settleAccount.setSettleNo(randId);
        }
        if(settleAccount.getSettleAmount() == null){
            return ResultVoUtil.error("结算金额不能为空。");
        }
        User curUser = userService.getId(ShiroUtil.getSubject().getId());
        MchInfo curMch = curUser.getMchInfo();
        Long totalAmount = payOrderService.sumPayAmountByOrderStatus
                (OrderStatus.PAY_SUCC,curMch.getMchNo());
        if(totalAmount == null){
            totalAmount = 0L;
        }
        if(totalAmount.compareTo(settleAccount.getSettleAmount()) <= 0){
            return ResultVoUtil.error("可结算金额不足，请重新输入结算金额.");
        }

        //手续费
        BigDecimal fee = curMch.getFee().multiply(new BigDecimal("0.01")).multiply(new BigDecimal("0.01"))
                .multiply(new BigDecimal(settleAccount.getSettleAmount()));
        settleAccount.setFee(fee);
        curMch.setSettleAmount(curMch.getSettleAmount()+settleAccount.getSettleAmount());//加
        userService.save(curUser);
        // 保存数据
        settleAccountService.save(settleAccount);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail")
    @RequiresPermissions("/settleAccount/detail")
    public String toDetail(@RequestParam("id") String id, Model model){
        SettleAccount settleAccount = settleAccountService.getId(id);
        model.addAttribute("settleAccount",settleAccount);
        return "/personMch/settleAccount/detail";
    }

    /**
     * 保存添加/修改的数据
     * @param settleAccountForm 表单验证对象
     */
    @PostMapping({"/audit"})
    @RequiresPermissions({"/settleAccount/add","/settleAccount/edit"})
    @ResponseBody
    @Transactional
    public ResultVo audit(@Validated SettleAccountForm settleAccountForm){
        if (!ShiroUtil.getSubject().getId().equals(AdminConst.ADMIN_ID)) {
            throw new ResultException(ResultEnum.NO_ADMIN_AUTH);
        }
        SettleAccount settleAccount = new SettleAccount();
        if(settleAccountForm.getId() != null){
            settleAccount = settleAccountService.getId(settleAccountForm.getId());
        }else{
            return ResultVoUtil.error("结算信息不存在。");
        }
        //FormBeanUtil.copyProperties(settleAccountForm, settleAccount);
        settleAccount.setRemark(settleAccountForm.getRemark());
        settleAccount.setSettleStatus(settleAccountForm.getSettleStatus());
        if(settleAccount.getSettleStatus().equals(SettleStatus.NO_PASS)){
            User curUser = userService.getId(settleAccount.getCreateBy().getId());
            MchInfo curMch = curUser.getMchInfo();
            curMch.setSettleAmount(curMch.getSettleAmount()-settleAccount.getSettleAmount());
            userService.save(curUser);
        }
        settleAccount.setAuditBy(ShiroUtil.getSubject().getId());
        settleAccount.setAuditDate(new Date());
        settleAccountService.save(settleAccount);
        return ResultVoUtil.success("审核完成！");
    }

    /**
     * 保存添加/修改的数据
     * @param settleAccountForm 表单验证对象
     */
    @PostMapping({"/pay"})
    @RequiresPermissions({"/settleAccount/add","/settleAccount/edit"})
    @ResponseBody
    public ResultVo pay(@Validated SettleAccountForm settleAccountForm){
        SettleAccount settleAccount = new SettleAccount();
        if(settleAccountForm.getId() != null){
            settleAccount = settleAccountService.getId(settleAccountForm.getId());
        }else{
            return ResultVoUtil.error("结算信息不存在。");
        }
        settleAccount.setPayAmount(settleAccountForm.getPayAmount());
        settleAccount.setSettleStatus(SettleStatus.DONE);
        settleAccount.setPayBy(ShiroUtil.getSubject().getId());
        settleAccount.setPayDate(new Date());
        settleAccountService.save(settleAccount);
        return ResultVoUtil.success("打款完成！");
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/toAudit")
    @RequiresPermissions("/settleAccount/edit")
    public String toAudit(@RequestParam("id") String id, Model model){
        SettleAccount settleAccount = settleAccountService.getId(id);
        model.addAttribute("settleAccount",settleAccount);
        return "/personMch/settleAccount/audit";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/toPay")
    @RequiresPermissions("/settleAccount/edit")
    public String toPay(@RequestParam("id") String id, Model model){
        SettleAccount settleAccount = settleAccountService.getId(id);
        model.addAttribute("settleAccount",settleAccount);
        return "/personMch/settleAccount/pay";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("/settleAccount/status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> idList){
        try {
            // 获取状态StatusEnum对象
            StatusEnum statusEnum = StatusEnum.valueOf(param.toUpperCase());
            // 更新状态
            //Integer count = settleAccountService.updateStatus(statusEnum,idList);
            /*if (count > 0){
                return ResultVoUtil.success(statusEnum.getMessage()+"成功");
            }else{
                return ResultVoUtil.error(statusEnum.getMessage()+"失败，请重新操作");
            }*/
            return ResultVoUtil.success();
        } catch (IllegalArgumentException e){
            throw new ResultException(ResultEnum.STATUS_ERROR);
        }
    }

}
